# -*- coding: utf-8 -*-
from myconn import MongoConn
import traceback
import pymongo
import time

ip = '192.168.31.244'  # '10.1.1.70'


def collection_names(dbname="FX"):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        return db.collection_names()
    except Exception:
        print(traceback.format_exc())


def collection_delete(dbname="singal", tablename='FXAUDCAD_1'):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        tb = db[tablename]
        tb.remove()
    except Exception:
        print(traceback.format_exc())

def finddb2(dbname="FX", tablename='FXUSDJPY', limit=200000, timetela=int(time.time())):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        table = db[tablename]
        res = list(table.find({"_id": {"$lt": timetela}}).sort("_id", 1))
        # res.reverse()
        datalist = []
        for one in res:
            if one["_id"] == 0:
                continue
            datalist.append({
                "Date": float(one["_id"]),
                "Open": float(one["open"]),
                "High": float(one["high"]),
                "Low": float(one["low"]),
                "Close": float(one["close"]),
                "DI": float(float(one["high"]) + float(one["low"]) + float(one["close"]) * 2) / 4,
            })
        return datalist
    except Exception:
        print(traceback.format_exc())

def finddb(dbname="FX", tablename='FXUSDJPY', limit=200000, timetela=int(time.time())):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        table = db[tablename]
        res = list(table.find({"_id": {"$lt": timetela}}).limit(limit).sort("_id", 1))
        # res.reverse()
        datalist = []
        for one in res:
            if one["_id"] == 0:
                continue
            datalist.append({
                "Date": float(one["_id"]),
                "Open": float(one["open"]),
                "High": float(one["high"]),
                "Low": float(one["low"]),
                "Close": float(one["close"]),
                "DI": float(float(one["high"]) + float(one["low"]) + float(one["close"]) * 2) / 4,
            })
        return datalist
    except Exception:
        print(traceback.format_exc())


def insertdb(data, dbname="huobi", tablename='cmteth_1min'):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        table = db[tablename]
        table.insert(data)
    except Exception:
        print(traceback.format_exc())


def savedb(data, dbname="huobi", tablename='cmteth_1min'):
    try:
        connection = pymongo.MongoClient(ip, 27017)
        db = connection[dbname]
        table = db[tablename]
        table.save(data)
    except Exception:
        print(traceback.format_exc())


def check_connected(conn):
    # +检查是否连接成功
    if not conn.connected:
        raise NameError('stat:connected Error')


def save(table, value):
    # 一次操作一条记录，根据‘_id’是否存在，决定插入或更新记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].save(value)
    except Exception:
        print(traceback.format_exc())


def insert(table, value):
    # 可以使用insert直接一次性向mongoDB插入整个列表，也可以插入单条记录，但是'_id'重复会报错
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].insert(value, continue_on_error=True)
    except Exception:
        print(traceback.format_exc())


def update(table, conditions, value, s_upsert=False, s_multi=False):
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].update(conditions, value, upsert=s_upsert, multi=s_multi)
    except Exception:
        print(traceback.format_exc())


def upsert_mary(table, datas):
    # 批量更新插入，根据‘_id’更新或插入多条记录。
    # 把'_id'值不存在的记录，插入数据库。'_id'值存在，则更新记录。
    # 如果更新的字段在mongo中不存在，则直接新增一个字段
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        bulk = my_conn.db[table].initialize_ordered_bulk_op()
        for data in datas:
            _id = data['_id']
            bulk.find({'_id': _id}).upsert().update({'$set': data})
        bulk.execute()
    except Exception:
        print(traceback.format_exc())


def upsert_one(table, data):
    # 更新插入，根据‘_id’更新一条记录，如果‘_id’的值不存在，则插入一条记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        query = {'_id': data.get('_id', '')}
        if not my_conn.db[table].find_one(query):
            my_conn.db[table].insert(data)
        else:
            data.pop('_id')  # 删除'_id'键
            my_conn.db[table].update(query, {'$set': data})
    except Exception:
        print(traceback.format_exc())


def find_one(table, value):
    # 根据条件进行查询，返回一条记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find_one(value)
    except Exception:
        print(traceback.format_exc())


def find(table, value):
    # 根据条件进行查询，返回所有记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find(value)
    except Exception:
        print(traceback.format_exc())


def select_colum(table, value, colum):
    # 查询指定列的所有值
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find(value, {colum: 1})
    except Exception:
        print(traceback.format_exc())


if __name__ == "__main__":
    # file_path = './enterprise_all.txt'
    # company_list = []
    # with open(file_path, "r") as in_file:
    #     for line in in_file:
    #         dic={}
    #         dic['_id']=line.strip()
    #         dic['name']=line.strip()
    #         company_list.append(dic)
    # upsert_mary('mytest',company_list)

    datas = [
        {'_id': 8, 'data': 88},
        {'_id': 9, 'data': 99},
        {'_id': 36, 'data': 3366}
    ]

    # 插入,'_id' 的值必须不存在，否则报错
    insert('mytest', datas)
    # 插入
    data = {'_id': 6, 'data': 66}
    save('mytest', data)
    # 更新数据
    update('mytest', {'_id': 8}, {'$set': {'data': '888'}}, False, False)
    # 更新或插入
    data = {'_id': 36, 'data': 'dsd'}
    upsert_one('mytest', data)
    # 查找。相对于 select _id from mytest
    res = select_colum('mytest', {}, '_id')
    for k in res:
        for key, value in k.items():
            print(key, ":", value)
    # 查找。相对于 select * from mytest
    res = find('mytest', {})
    for k in res:
        for key, value in k.items():
            print(key, ":", value, )
        print
    # 查找。相对于 select * from mytest limit 1
    res = find_one('mytest', {})
    for k in res:
        print(k, ':', res[k])
